package com.spark.common.ext

import android.app.Activity
import android.content.ComponentName
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS

/**
 * 进入应用程序的权限设置页手动开关权限
 */

fun Activity.permissionSettings() {
    val mark = Build.MANUFACTURER.toLowerCase()
    try {
        when (mark) {
            "huawei" -> huaweiPermSetting()
            "xiaomi" -> xiaomiPermSetting()
            "oppo" -> oppoPermSetting()
            "vivo" -> vivoPermSetting()
            "samsung" -> boomPermSetting()
            "meizu" -> meizuPermSetting()
            "smartisan" -> smartisanPermSetting()
            else -> permSetting()
        }
    } catch (e: Exception) {
        e.printStackTrace()
        permSetting()
    }

}

/**
 * 普通手机进入设置页
 */
private fun Activity.permSetting() {
    val intent = Intent(ACTION_APPLICATION_DETAILS_SETTINGS)
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    intent.data = Uri.fromParts("package", packageName, null)
    startActivity(intent)
}

/**
 * Huawei
 * api < 23
 */
private fun Activity.huaweiPermSetting() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        permSetting()
        return
    }
    val intent = Intent()
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    intent.component = ComponentName("com.huawei.systemmanager", "com.huawei.permissionmanager.ui.MainActivity")
    startActivity(intent)
}

/**
 * xiaomi
 */
private fun Activity.xiaomiPermSetting() {
    val intent = Intent("miui.intent.action.APP_PERM_EDITOR")
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    intent.putExtra("extra_pkgname", packageName)
    startActivity(intent)
}

/**
 * vivo
 */
private fun Activity.vivoPermSetting() {
    val intent = Intent()
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    intent.putExtra("packagename", packageName)
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
        intent.component = ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.SoftPermissionDetailActivity")
    } else {
        intent.component = ComponentName("com.iqoo.secure", "com.iqoo.secure.safeguard.SoftPermissionDetailActivity")
    }
    startActivity(intent)
}

/**
 * oppo
 */
private fun Activity.oppoPermSetting() {
    permSetting()
}

/**
 * meizu
 */
private fun Activity.meizuPermSetting() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
        permSetting()
        return
    }
    val intent = Intent("com.meizu.safe.security.SHOW_APPSEC")
    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
    intent.putExtra("packageName", packageName)
    intent.component = ComponentName("com.meizu.safe", "com.meizu.safe.security.AppSecActivity")
    startActivity(intent)
}

/**
 * 锤子🔨
 */
private fun Activity.smartisanPermSetting() {
    permSetting()
}

/**
 * Samsung
 */
private fun Activity.boomPermSetting() {
    permSetting()
}